package cn.tedu.ivos2.user.service.impl;

import cn.tedu.ivos2.base.exception.ServiceException;
import cn.tedu.ivos2.base.response.StatusCode;
import cn.tedu.ivos2.user.mapper.UserMapper;
import cn.tedu.ivos2.user.pojo.dto.UserLoginParam;
import cn.tedu.ivos2.user.pojo.dto.UserQuery;
import cn.tedu.ivos2.user.pojo.dto.UserSaveParam;
import cn.tedu.ivos2.user.pojo.entity.User;
import cn.tedu.ivos2.user.pojo.vo.UserVO;
import cn.tedu.ivos2.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @author 边拾柱
 * @date 2024/12/13 16:55
 */
@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    public UserVO login(UserLoginParam userLoginParam) {
        log.debug("开始执行【用户登录】业务层方法");
        UserVO userVO = userMapper.selectByUsername(userLoginParam.getUsername());
        if (userVO == null) {
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }
        if (!userLoginParam.getPassword().equals(userVO.getPassword())) {
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }

        return userVO;
    }

    @Override
    public List<UserVO> selectUser(UserQuery userQuery) {
        log.debug("开始执行查询用户信息：{}", userQuery);
        return userMapper.selectUser(userQuery);
    }

    @Override
    public void saveUserInfo(UserSaveParam userSaveParam) {
        log.debug("开始执行保存或更新用户信息：{}", userSaveParam);
        User user = new User();
        BeanUtils.copyProperties(userSaveParam, user);
        if (user.getId() != null) {

            user.setUpdateTime(new Date());
            userMapper.update(user);
        } else {
            user.setPassword("123456");
            user.setCreateTime(new Date());
            userMapper.insert(user);
        }
    }

    @Override
    public List<UserVO> selectAllUser(UserQuery userQuery) {
        List<UserVO> userVOS = userMapper.selectAllUser(userQuery);
        return userVOS;
    }

    @Override
    public void resetPassword(Long id) {
//        userMapper.resetPassword(id);
        User user = new User();
        user.setId(id);
        user.setPassword("admin");
        userMapper.update(user);
    }

    @Override
    public void deleteByUserId(Long userId) {
        log.debug("删除用户业务操作，userId={}",userId);
        userMapper.deleteByUserId(userId);
    }

    @Override
    public void updateUserStatus(Long id, String status) {
        User user = new User();
        user.setId(id);
        user.setStatus(status);
        user.setUpdateTime(new Date());
        userMapper.update(user);
    }


}
